<template>
  <div>
    <public-modal
      width="900px"
      :footer="false"
      :title="title"
      :publicVisible="publicVisible"
      @handleOk="handleOk"
      @cancel="cancel"
    >
      <div slot="content" class="form-wrapper">
        <a-form-model
          ref="form"
          :model="form"
          :rules="rules"
          class="form-table-style"
          autocomplete="off"
          layout="inline"
          labelAlign="left"
          :labelCol="{ style: 'width: 140px' }"
        >
          <a-row type="flex">
            <a-col flex="auto">
              <a-row type="flex">
                <a-col flex="auto">
                  <a-form-model-item label="患者姓名" prop="name" :colon="false">
                    <a-input :maxLength="30" autocomplete="off" placeholder="请输入" v-model="form.name" />
                  </a-form-model-item>
                </a-col>
                <a-col flex="360px">
                  <a-form-model-item label="身份证号" prop="idCard" :colon="false">
                    <a-input :maxLength="30" autocomplete="off" placeholder="请输入" v-model="form.idCard" />
                  </a-form-model-item>
                </a-col>
              </a-row>

              <a-row type="flex">
                <a-col flex="auto">
                  <a-form-model-item label="民族" prop="nation" :colon="false">
                    <a-select allowClear v-model="form.nation" placeholder="请选择">
                      <a-select-option :value="item.value" v-for="(item, index) in nationList" :key="index">
                        {{ item.text }}</a-select-option
                      >
                    </a-select>
                  </a-form-model-item>
                </a-col>
                <a-col flex="360px">
                  <a-form-model-item label="血型" prop="bloodType" :colon="false">
                    <a-select allowClear v-model="form.bloodType" placeholder="请选择">
                      <a-select-option :value="item.value" v-for="(item, index) in bloodList" :key="index">
                        {{ item.text }}</a-select-option
                      >
                    </a-select>
                  </a-form-model-item>
                </a-col>
              </a-row>

              <a-row type="flex">
                <a-col flex="auto">
                  <a-form-model-item label="精神障碍等级" prop="patientLevel" :colon="false">
                    <a-select allowClear v-model="form.patientLevel" placeholder="请选择">
                      <a-select-option :value="0"> 0 </a-select-option>
                      <a-select-option :value="1"> 1 </a-select-option>
                      <a-select-option :value="2"> 2 </a-select-option>
                      <a-select-option :value="3"> 3 </a-select-option>
                      <a-select-option :value="4"> 4 </a-select-option>
                      <a-select-option :value="5"> 5 </a-select-option>
                    </a-select>
                  </a-form-model-item>
                </a-col>
                <a-col flex="360px">
                  <a-form-model-item label="判定时间" prop="judgmentTime" :colon="false">
                    <a-date-picker v-model="form.judgmentTime" placeholder="请选择" />
                  </a-form-model-item>
                </a-col>
              </a-row>
            </a-col>
            <a-col flex="120px">
              <a-form-model-item label="">
                <a-upload
                  :file-list="fileList"
                  name="avatar"
                  list-type="picture-card"
                  class="avatar-uploader"
                  :customRequest="customRequest"
                  ref="uploadImgRef"
                  :remove="remove"
                  @preview="handlePreview(imageUrl)"
                >
                </a-upload>
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row type="flex">
            <a-col flex="auto">
              <a-form-model-item label="判定单位" prop="judgmentUnit" :colon="false">
                <a-input :maxLength="30" autocomplete="off" placeholder="请输入" v-model="form.judgmentUnit" />
              </a-form-model-item>
            </a-col>
            <a-col flex="480px" class="right-box-width">
              <a-form-model-item label="责任医疗机构" :colon="false">
                <a-input
                  :maxLength="30"
                  autocomplete="off"
                  placeholder="请输入"
                  v-model="form.responsibleOrganization"
                />
              </a-form-model-item>
            </a-col>
          </a-row>

          <a-row type="flex">
            <a-col flex="auto">
              <a-form-model-item label="居住地址" prop="currentAddress" :colon="false">
                <a-input :maxLength="30" autocomplete="off" placeholder="请输入" v-model="form.currentAddress" />
              </a-form-model-item>
            </a-col>
          </a-row>

          <a-row type="flex">
            <a-col flex="auto">
              <a-form-model-item label="管辖派出所" prop="userName" :colon="false">
                <a-input
                  :maxLength="30"
                  autocomplete="off"
                  placeholder="请输入"
                  disabled
                  v-model="form.policeAgencyName"
                />
              </a-form-model-item>
            </a-col>
            <a-col flex="480px" class="right-box-width">
              <a-form-model-item label="所属责任区" prop="userName" :colon="false">
                <a-select
                  v-model="form.policeJurisdictionId"
                  ref="select"
                  show-search
                  placeholder="请选责任区"
                  class="select-jurisdiction"
                >
                  <a-select-option
                    :value="item.id"
                    v-for="(item, index) in provideData().jurisdictionList"
                    :key="index"
                    >{{ item.jurisdictionName }}</a-select-option
                  >
                </a-select>
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-form-model>
      </div>
    </public-modal>
  </div>
</template>

<script>
import { uploadFile } from '@/api/api'
import { checkIDCard } from '@/utils/validate.js'
import publicModal from '@/components/publicModal'
import { putAction, postAction } from '@/api/manage'
import { isMobile } from '@/utils/validate'
import { getDictItemsFromCache } from '../../../../api/api'
import { getPrefixImg, previewImage } from '../../../../utils/util'
import moment from 'moment'
import { getFileAccessHttpUrl } from '../../../../api/manage'

export default {
  name: 'addPatientModal',
  components: { publicModal },
  props: {
    institution: {
      type: Object,
      default: () => ({}),
    },
  },
  data() {
    return {
      title: '新增',
      record: {},
      status: 0,
      publicVisible: false,
      imageUrl: [],
      fileList: [],
      showUploadList: { showPreviewIcon: false },
      form: {},
      rules: {
        name: [{ required: true, message: '请输入!' }],
        patientLevel: [{ required: true, message: '请选择精神障碍等级!' }],
        idCard: [
          { required: true, message: '请输入!' },
          {
            validator: (rule, value, callback) => {
              if (!checkIDCard(value)) {
                callback(new Error('请输入正确的身份证号'))
              } else {
                callback()
              }
            },
          },
        ],
        currentAddress: [{ required: true, message: '请输入!' }],
      },
      nationList: getDictItemsFromCache('nation'),
      bloodList: getDictItemsFromCache('blood_type'),
      actionType: '',
      uploadImgRef: null,
      imgPrefix: getPrefixImg(),
    }
  },
  inject: ['provideData'],
  mounted() {},
  methods: {
    async show(record = {}, actionType = 'add') {
      this.actionType = actionType
      this.record = record
      this.publicVisible = true

      if (actionType == 'edit') {
        this.title = `编辑患者`
        this.form = { ...record }
        console.log(this.form)
        if (record.userImg) {
          const obj = {
            uid: record.userImg,
            name: record.userImg,
            status: 'done',
            url: this.imgPrefix + record.userImg,
          }
          this.fileList = [obj]
          this.imageUrl = [{ halfPath: record.userImg }]
        }
      } else {
        this.title = `新增患者`
        this.$set(this.form, 'policeAgencyName', this.institution.policeAgencyName)
      }
    },

    remove(file) {
      console.log('remove')
      let uid = file.uid
      let index = this.fileList.findIndex((v) => {
        return v.uid == uid
      })
      this.fileList.splice(index, 1)
      this.imageUrl.splice(index, 1)
      // 上传完成之后，隐藏上传框
      let uploadDom = this.$refs.uploadImgRef.$el.getElementsByClassName('ant-upload-select-picture-card')[0]
      uploadDom.style.display = 'flex'
    },
    async customRequest(info) {
      let file = info.file
      const formData = new FormData()
      formData.append('file', file)
      formData.append('type', 2)
      let res = await uploadFile(formData)
      if (res.code == 200) {
        this.imageUrl = [res.result]
        this.fileList = [res.result].map((item, index) => {
          return {
            uid: index,
            status: 'done',
            url: item.fullPath,
          }
        })

        // 上传完成之后，隐藏上传框
        let uploadDom = this.$refs.uploadImgRef.$el.getElementsByClassName('ant-upload-select-picture-card')[0]
        uploadDom.style.display = 'none !important'
      }
    },
    uploadChange({ file, fileList }) {
      file.status = 'done'
      this.fileList = fileList
    },

    handleOk() {
      this.$refs.form.validate(async (valid) => {
        if (!valid) return
        let url = ''
        if (this.actionType == 'add') {
          url = '/wb/mentalpatient/addMentalPatient'
        } else {
          url = '/wb/mentalpatient/addMentalPatient'
        }
        const method = this.record.id ? postAction : postAction
        try {
          const res = await method(url, {
            ...this.form,
            policeAgencyId: this.institution.id,
            userImg: this.imageUrl.map((item) => item.halfPath).join(','),
            judgmentTime: moment(this.form.judgmentTime).format('yyyy/MM/DD HH:mm:ss'),
          })
          this.$message.success(res.message)
          this.$emit('refresh')
          this.cancel()
        } catch (error) {
          // 处理错误
          console.error('请求失败:', error)
          this.$message.error('请求失败，请稍后重试！')
        }
      })
    },

    cancel() {
      this.publicVisible = false
      this.fileList = []
      this.imageUrl = []
      this.form = {}
    },
    handlePreview(urls = []) {
      urls = urls.map((item) => item.halfPath)
      previewImage.call(this, urls)
    },
  },
}
</script>

<style scoped lang="less">
.formStyle {
  padding: 0.2rem;
  /deep/.ant-col {
    height: unset;
  }
  .ant-form-inline .ant-form-item-with-help {
    margin-bottom: 5px;
  }
}
.form-wrapper {
  padding: 32px 25px 20px 25px;
  /deep/.avatar-uploader {
    height: 136px;
    width: 120px;

    .ant-upload {
      width: 100%;
      height: 100%;
      background: unset;
      border: 0;
      height: 136px;
      width: 120px;
      display: flex !important;
    }
    .upload-img {
      height: 136px;
      width: 120px;
    }
    .ant-upload-list-picture-card-container,
    .ant-upload-list-item {
      height: 136px;
      width: 120px;
    }
    .ant-upload-select-picture-card {
      background: url('../../../../assets/imgs/upload-img-bg.png') no-repeat;
      background-size: 100% 100%;
    }
    .ant-upload-list-item {
      border: 1px solid #0855cc;
    }
  }
  .form-table-style {
    /deep/.ant-form-item-label {
      background: #084dbe;
      border: 1px solid #0855cc;
      padding-left: 12px;
      height: 100%;
      flex-shrink: 0;
      > label {
        font-weight: 500;
        font-size: 14px;
        color: #8fbbff;
      }
    }
    /deep/.ant-form-explain {
      position: absolute;
      z-index: 10;
      bottom: -5px;
      left: 10px;
    }
    /deep/.ant-form-item-control-wrapper {
      flex: 1;
      height: 100%;
    }
    /deep/.ant-form-item {
      align-items: stretch;
      margin-right: 0;
      height: 46px;
      display: flex;
    }
    /deep/.ant-form-item-with-help {
      margin-right: 0;
      margin-bottom: 0;
    }
    /deep/.ant-form-item-control {
      height: 100%;
      .ant-form-item-children {
        height: 100%;
        display: block;
        .ant-input {
          height: 100%;
          background: #07429e;
          border-radius: 0px 0px 0px 0px;
          border: 1px solid #0855cc;
          color: #fff;
          &::placeholder {
            color: #6ea7ff;
          }
        }
        .ant-select {
          height: 100%;
          vertical-align: top;
        }

        .ant-calendar-picker {
          height: 100%;
          > div {
            height: 100%;
          }
        }
        .ant-select-selection {
          height: 100%;
          background: #0a49af;
          border: 0;
          border-radius: 0;
        }
        .select-jurisdiction {
          width: 339px;
        }

        .ant-select-selection__rendered {
          height: 100%;
        }
        .ant-select-selection-selected-value {
          line-height: 42px;
          color: #fff;
        }
        .ant-select-selection__placeholder {
          color: #6ea7ff;
        }
      }
    }
    .right-box-width {
      max-width: 480px;
    }
  }
}

.imageUpload {
  margin-bottom: 150px;
  /deep/.avatar-uploader {
    > .ant-upload {
      width: 150px;
      height: 176px;
      background: var(--theme-input-bg);
      border: 1px solid var(--theme-input-border);
    }
  }

  /deep/.ant-upload-select-picture-card {
    width: 150px;
    height: 176px;
  }

  /deep/ .ant-upload-list-item {
    width: 150px;
    height: 176px;
  }

  .imgText {
    color: #1163b8;
    font-weight: 500;
  }

  .pictIcon {
    margin-bottom: 10px;
    width: 42px;
    height: 38px;
  }
}
</style>
